package com.example.workflow.config;


import com.example.workflow.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {


    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;


    //    使用SpringSecurity为我们提供的BCryptPasswordEncoder，进行加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


//    public void configure(HttpSecurity http) throws Exception {
//        http
//                .csrf().disable()
//                .authorizeRequests(auth -> auth
//                        .requestMatchers("/admin/**").hasRole("ADMIN")
//                        .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
//                        .requestMatchers("/", "/home", "/register").permitAll()
//                        .anyRequest().authenticated()
//                )
//                .formLogin(form -> form
//                        .loginPage("/login")
//                        .permitAll()
//                        .successHandler(authenticationSuccessHandler)
//                        .failureHandler(authenticationFailureHandler)
//                )
//                .logout(LogoutConfigurer::permitAll
//                );
//        http.addFilter(jwtAuthenticationTokenFilter);
//    }



    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/engine-rest").permitAll()
                        .requestMatchers("/camunda/**", "/api/**", "/lib/**").permitAll()
                        .requestMatchers("/engine-rest/**").permitAll()
                        .requestMatchers("/user/login").permitAll()
                        .requestMatchers("/**").permitAll()
                        .anyRequest().authenticated()
                )
                // 认证异常处理 -- 测试授权异常时，可以注释掉DemoAuthenticationEntryPoint
                // 授权异常处理
//                .formLogin(form -> form
//                        .loginPage("https://www.bilibili.com/") // 跳转自定义登录表单界面
//                        .defaultSuccessUrl("/welcome", true)
//                        .permitAll()
//                        .successHandler(authenticationSuccessHandler) // 成功处理方法
//                        .failureHandler(authenticationFailureHandler) // 失败处理方法
//                )
//                .formLogin(AbstractHttpConfigurer::disable) // ✅ 禁用表单登录，不让它干扰接口
                // 完全禁用表单登录（不生成默认登录页）
                .formLogin(AbstractHttpConfigurer::disable)
                // 自定义认证入口点（未登录时返回JSON）
                .exceptionHandling(
                        httpSecurityExceptionHandlingConfigurer ->
                                httpSecurityExceptionHandlingConfigurer
                                        .authenticationEntryPoint(authenticationEntryPoint)
                                        // 认证异常处理 -- 测试授权异常时，可以注释掉DemoAuthenticationEntryPoint
                                        // 授权异常处理
                                        .accessDeniedHandler(accessDeniedHandler)
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/login")          // 跳转自定义登录表单界面
                        .logoutSuccessHandler(logoutSuccessHandler));
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}
